package cn.tedu._04weibo.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {

    private static final int MAX_REQUEST_COUNT = 3;
    private static final int REQUEST_TIME_WINDOW = 60;
    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastRestreatTime = new ConcurrentHashMap<>();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("访问次数限制");
        String clientIp = request.getRemoteAddr();
        LocalDateTime now = lastRestreatTime.get(clientIp);
        if(now==null||LocalDateTime.now().isAfter(now.plusSeconds(REQUEST_TIME_WINDOW))){
            lastRestreatTime.put(clientIp,LocalDateTime.now());
            clientCounts.put(clientIp,0);
        }
        int count = clientCounts.get(clientIp);
        count=count+1;
        clientCounts.put(clientIp,count);
        log.debug("当前访问次数为：{}",count);
        if(count>MAX_REQUEST_COUNT){
            throw new RuntimeException("访问次数过于频繁，请稍后重试.......");
        }

        return true;
    }
}
